<?php

class IndexController extends Zend_Controller_Action
{
	public function init()
	{
		// Get the logging status of the person
		$this->view->logged = Zend_Auth::getInstance()->hasIdentity();
		
		// A Décommenter si on veut utiliser la redirection sur SSL
		//Perso_ConfigSSL::config();
	}
	
	public function indexAction()
	{
		// Set display the login sidebar
		$this->view->active = true;
		$this->view->mainIndex = true;

        $this->view->loginForm = $this->view->action('login', 'index');
		//$this->view->demoDiagramm = $this->view->action('showdiagramm', 'index');
			
		// If the person is logged, redirect him to its project list
		if(Zend_Auth::getInstance()->hasIdentity()) {
			$this->_redirect('listproject/index');
		}
		
		
		// Set display the demo diagramm
		$this->view->isDemo = true;
		
		// Add The requested JS library
		$baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl();
		$this->view->headScript()->appendFile($baseUrl.'/js/jquery-1.3.2.js');
		$this->view->headScript()->appendFile($baseUrl.'/js/ui/jquery-ui-1.7.2.custom.js');
		$this->view->headScript()->appendFile($baseUrl.'/js/nestedSortables/interface-1.2.js');
		$this->view->headScript()->appendFile($baseUrl.'/js/nestedSortables	/inestedsortable.js');
		$this->view->headScript()->appendFile($baseUrl.'/js/contextmenu/jquery.contextMenu.js');

		// Load css for the diagramm 
		$this->view->headLink()->prependStylesheet($baseUrl.'/css/jquery-ui-1.7.2.custom.css');
		$this->view->headLink()->prependStylesheet($baseUrl.'/css/jquery.contextMenu.css');	
		$this->view->headLink()->prependStylesheet($baseUrl.'/css/diagramm.css');
		
		// Load homepage css
		$this->view->headLink()->prependStylesheet($baseUrl.'/css/homepage.css');
	}
	
	
	public function loginAction()
	{
		// Display the login sidebar
		$this->view->active = true;
		$this->view->mainIndex = false;
		
		// If the person is logged, redirect him to its project list
		if(Zend_Auth::getInstance()->hasIdentity()) {
			$this->_redirect('listproject/index');
		}

		require_once APPLICATION_PATH . '/models/DbTable/Person.php';
		require_once APPLICATION_PATH . '/forms/LoginForm.php';

		$users = new Person();
		$form = new LoginForm();
		
		// Retrieve the login form
		$this->view->loginForm = $form;

		// Check if data were submitted
		if($this->getRequest()->isPost()){
			// Check if the data form's are valid
			if($form->isValid($_POST)){
				// Retrieve the values from the form
				$data = $form->getValues();
				
				// escape the data
				$data['username'] = htmlentities($data['username']);
				$data['password'] = htmlentities($data['password']);

				$auth = Zend_Auth::getInstance();
				// Get an access to the DB
				$authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter(),'Person');
				// Retrieve the username and password hash from the database
				$authAdapter
					->setIdentityColumn('username')
					->setCredentialColumn('password');
				
				// Retrieve the username and password hash from the form
				$authAdapter
					->setIdentity($data['username'])
					->setCredential(hash('sha256', $data['password']));
				
				// Compare the data from the database with the data submitted			
				$result = $auth->authenticate($authAdapter);
				
				// if the username and password match
				if($result->isValid()) {
					// write the username and idPerson in the session for easy access later
					$storage = new Zend_Auth_Storage_Session();
					$storage->write($authAdapter->getResultRowObject(array('username','idPerson')));
					// Redirect the user to its project list
					$this->_redirect('listproject/index');
				} else {
					// Give the error message to the view
					$this->view->errormessage ="Invalid username or password. Please try again.\n";
				}         
			}
		}
	}
	
	public function passwordlostAction()
	{	
		// Display the login sidebar
		$this->view->active = false;
		$this->view->mainIndex = false;
		
		// If the person is logged, redirect him to its project list
		if(Zend_Auth::getInstance()->hasIdentity()) {
			$this->_redirect('listproject/index');
		}
		require_once APPLICATION_PATH . '/models/DbTable/Person.php';
		require_once APPLICATION_PATH . '/forms/PasswordrecoveryForm.php';

		$form = new PasswordrecoveryForm();
		
		// Retrieve the password recovery form
		$this->view->form = $form;
		
		// Check if data were submitted
		if ($this->getRequest()->isPost()){		
			// Check if the data form's are valid and if the username submitted is in the database (checked in the form)
			if ($form->isValid($_POST)){
				// Retrieve the values from the form
				$data = $form->getValues();
				$username = $data['username'];
				
	            // Generate random password of 10 characters
				$password = $this->randomPassword(10);

				$user = new Person();
				$user->setUserPassword($username, $password);

				// Send an email with the new password
		        $this->sendEmail($user->getUserEmail($username), $password);
	            $this->_redirect('index/index');
			}			
		}
		
		// Load pwdrecover css
		$baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl();
		$this->view->headLink()->prependStylesheet($baseUrl.'/css/pwdrecover.css');
	}
            
    public function createaccountAction()
    {	
    	// Hide the login sidebar
   		$this->view->active = false;
		$this->view->mainIndex = false;
		
		// If the person is logged, redirect him to its project list
		if(Zend_Auth::getInstance()->hasIdentity()) {
			$this->_redirect('listproject/index');
		}
				
		require_once APPLICATION_PATH . '/forms/RegistrationForm.php';
		
		$form = new RegistrationForm();
		
		// Retrieve the registration form
		$this->view->form = $form;

		// Check if data were submitted
		if ($this->getRequest()->isPost()) {		
			// Check if the data form's are valid 
			if ($form->isValid($_POST)) {	
				// Retrieve the values from the form
				$data = $form->getValues();
				
				// Create a Person object to access the database
				require_once APPLICATION_PATH . '/models/DbTable/Person.php';
				$newUser = new Person();

				// Free the confirmPassword and captcha
				unset($data['confirmPassword']);
				unset($data['captcha']);
				
				// Process the password hash and escape all fields
				$data['password'] = hash('sha256',htmlentities($data['password']));
				$data['name'] = htmlentities($data['name']);
				$data['email'] = htmlentities($data['email']);
				$data['tel'] = htmlentities($data['tel']);
				$data['username'] = htmlentities($data['username']);
				
				// Store the new user in the database
				$newUser->insert($data);
				
				// Redirect the user to its project list
				$this->_redirect('index/index');
			}
		}
		
			// Load form css
			$baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl();
			$this->view->headLink()->prependStylesheet($baseUrl.'/css/form.css');
    }

    public function logoutAction()
    {
    	// Activate the login sidebar
   		$this->view->active = true;
		$this->view->mainIndex = false;
		
   		// Clear the session
        $storage = new Zend_Auth_Storage_Session();
        $storage->clear();
        
        // Redirect the user to the login page
        $this->_redirect('index/index');
    }
    
    // Generate a random password from the lenght required
    private function randomPassword($length) 
	{
		$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		return substr(str_shuffle($chars),0 ,$length);
	}
	    
    // Send an email with the new Password
    private function sendEmail($email,$result)
    {
    	// Prepare the mail server
        $mail  = new Zend_Mail();
        $tr    = new Zend_Mail_Transport_Smtp('smtpgw1.he-arc.ch');
        
        // Prepare the email
        $mail->setBodyText("Dear ".$email.",\n\n
You have successfully changed your password.\n
Your new password is : ".$result."\n
It doesn't require any confirmation and your old password is lost.\n\n
Thank you for using Gantt4Web,\n
Best regards,\n
Gantt4Web team
        ");
        $mail->setFrom("info@gantt4web.ch", "Gantt4Web");
        $mail->addTo("$email", "");
        $mail->setSubject("Gantt4Web : New password generated");
        
        // Send the email
       	if($mail->send($tr))
            echo "Please consult your emails. ";
        else {
            echo "Mail sending error.\n Please contact the Webmaster.";
        }
    }
}
